package dao.jpa;

import dao.CursoDAO;
import java.util.List;
import javax.persistence.NoResultException;
import modelo.Curso;
import javax.persistence.Query;
import util.JPAUtil;

/**
 *
 * @author Jorge
 */
public class CursoJpaDAO extends AbstractJpaDao<Curso, Long> implements CursoDAO {

    public CursoJpaDAO() {
        super(Curso.class);
    }

    @Override
    public List<Curso> getAll() {
        String s = "from Curso";
        Query query = JPAUtil.getEntityManager().createQuery(s);

        return query.getResultList();
    }

    public Curso getPorId(Long id) {
        String s = "select c from Curso c where c.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        try {
            return (Curso) query.getSingleResult();
        }
        catch(NoResultException e) {
            return null;
        }
    }

    public List<Curso> getPorNome(String nome) {
        String s = "select c from Curso c where upper(c.nome) like upper(?)";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, "%" + nome + "%");

        return (List<Curso>) query.getResultList();
    }

    public Curso getPorIdComDisciplinas(Long id) {
        String s = "select c from Curso c " +
                   "left outer join fetch c.listaDisciplinas ad " +
                   "where c.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        return (Curso) query.getSingleResult();
    }
}
